<?php

/**
 * Maikuro CMS
 *
 * LICENSE:
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * The license is bundled with this package in the file LICENSE.txt.
 * You may also obtain a copy of the License at this URL:
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @copyright  Copyright (c) 2010, Jonathan Hedrén
 * @author     Jonathan Hedrén <jonathan.hedren@gmail.com>
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 */


final class LoginViewController implements IViewController
{
    /**
     *
     * @var BackendApplicationContext
     */
    private $applicationContext;

    /**
     *
     * @var AdministratorService
     */
    private $administratorService;

    /**
     *
     * @param BackendApplicationContext $applicationContext
     * @param AdministratorService $administratorService
     */
    public function  __construct(BackendApplicationContext $applicationContext, AdministratorService $administratorService) {
        $this->applicationContext = $applicationContext;
        $this->administratorService = $administratorService;
    }

    /**
     *
     * @param Request $request
     * @param Response $response
     * @param View $view
     */
    public function handleRequest(Request $request, Response $response, View $view)
    {
        if (Auth::isAuthenticated() && $this->applicationContext->getSessionUser() != null) {
            $request->redirectTo('');
        }
        
        if ($request->getParam(0) == 'forgotpassword') {
            if ($request->isPost()) {
                $resetPasswordForm = new RequestResetCodeForm();
                $this->handleOnForgotPasswordFormSubmit($loginForm, $request);
            }
            $view->setName('login/forgotpassword');
        } else if ($request->getParam(0) == 'resetpassword') {
            if ($request->isPost()) {
                $resetPasswordForm = new ResetPasswordForm();
                $this->handleOnForgotPasswordFormSubmit($loginForm, $request);
            }
            $view->setName('login/resetpassword');
        } else {

            $loginForm = new LoginForm();
            if ($request->isPost()) {
                $this->handleOnLoginFormSubmit($loginForm, $request);
            }
        }
        
        $viewModel = new ViewModel();

        $this->applicationContext->getEventHandler()->dispatchEvent(Constants::EVENT_VIEW_PRE_RENDER, $viewModel);
        
        $view->setVar('viewModel', $viewModel);
        
        $view->render();
    }

    /**
     *
     * @param LoginForm $loginForm
     * @param Request $request
     */
    private function handleOnLoginFormSubmit(LoginForm $loginForm, Request $request)
    {
        $loginForm->setData($request->getPost());
        if ($loginForm->isValid()) {
            $username = $loginForm->username;
            if (Validators::email($username)) {
                $administrator = $this->administratorService->getAdministratorByEmail($username);
            } else {
                $administrator = $this->administratorService->getAdministratorByUsername($username);
            }

            if ($administrator === null ||
                !Auth::authenticate($loginForm->password, $administrator->password, $administrator->created)) {
                View::getMessenger()->addMessage('Unknown user or password.');
                $request->redirectTo($request->getUri());
            }

            $sessionUser = new SessionUser($administrator->permissions, $administrator->id);
            $this->applicationContext->setSessionUser($sessionUser)
                                     ->setCurrentSite(null);

            $administrator->lastLogin = date("Y-m-d H:i:s");
            $this->administratorService->save($administrator);
            $this->administratorService->purgeCache();
            
            View::getMessenger()->addMessage('You are logged in.');
            $request->redirectTo($this->applicationContext->getPreviousRequestUri('/'));
        }
    }
}